local cmp = require('cmp')
local display = require('config.display')
local cmp_autopairs = require('nvim-autopairs.completion.cmp')
local luasnip = require('luasnip')


local function T(str)
  return vim.api.nvim_replace_termcodes(str, true, true, true)
end

local function setup()
  cmp.setup {
    formatting = {
      format = function (entry, vim_item)
        vim_item.kind = display.item_kind[vim_item.kind]
        vim_item.menu = ({
          nvim_lsp = "[LSP]",
          buffer= "[Buffer]",
          luasnip= "[Snippet]",
        })[entry.source.name]
        return vim_item
      end
    },
    snippet = {
      expand = function(args)
        require('luasnip').lsp_expand(args.body)
      end
    },
    mapping = {
      ["<C-p>"] = cmp.mapping.select_prev_item(),
      ["<C-n>"] = cmp.mapping.select_next_item(),
      ['<Tab>'] = cmp.mapping(function (fallback)
        if cmp.visible() then
          cmp.select_next_item()
        elseif luasnip.expand_or_jumpable() then
          vim.fn.feedkeys(T('<Plug>luasnip-expand-or-jump'), "")
        else
          fallback()
        end
      end, {'i', 's'}),
      ['<CR>'] = cmp.mapping.confirm({
        behavior = cmp.ConfirmBehavior.Replace,
        select = true,
      })
    },
    sources = {
      { name = 'luasnip' },
      { name = 'nvim_lsp' },
      { name = 'buffer' },
      { name = 'path' },
    }
  }

  cmp.event:on('confirm_done', cmp_autopairs.on_confirm_done({map_char = {tex = ''}}))
end

return {
  setup = setup
}
